package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.*;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsTranUpdateSaveCmd;
import com.jackrain.nea.fc.dl.mapper.WMSDLUpdateMapper;
import com.jackrain.nea.fc.dl.mapper.WmsOrderInMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 库存调整
 *
 * @author xuxinshuai
 * @date 2018/05/05
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsTranUpdateSaveCmdImpl extends CommandAdapter implements WmsTranUpdateSaveCmd {


    @Autowired
    PostDubbleEvent postDubbleEvent;
    @Autowired
    PostHandleEvent postHandleEvent;
    @Autowired
    QueryCpUtil postQueryEvemt;
    @Autowired
    QueryUserUtil postUserEvent;
    @Autowired
    private ElasticsearchUtil esUtil;
    @Autowired
    private ConvertQueryListUtil convertQLUtil;
    @Autowired
    private BtranEsName btranEsName;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsOrderInMapper wmsOrderInMapper = ApplicationContextHandle.getBean(WmsOrderInMapper.class);
        WMSDLUpdateMapper wmsdlUpdateMapper = ApplicationContextHandle.getBean(WMSDLUpdateMapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }
//        log.debug("----------库存调整----------" + param);
        log.info("WmsTranUpdateSaveCmdImpl-->param-->{}",param);

        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();

        JSONArray dataArray = param.getJSONArray("data");

        JSONArray queryDataArray = new JSONArray();
        JSONArray succesIdArray = new JSONArray();
        JSONArray errArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject dataJo = dataArray.getJSONObject(i);
            JSONObject oldJo = dataJo.getJSONObject("DL_B_INV_ADJ");
            JSONArray purInItemArray = dataJo.getJSONArray("DL_B_INV_ADJ_ITEM");

            String billnoid = oldJo.getString("ID");
            String wms_bill_no= oldJo.getString("WMS_BILL_NO");
            JSONObject stateObj = new JSONObject();
            Long objid = oldJo.getLong("OBJID");    //返回ID
            int state = oldJo.getInteger("STATE"); //执行步骤

            try {

                JSONObject fixColumn = dataConversion(oldJo, purInItemArray, wmsOrderInMapper);
                User user = postUserEvent.getUser(UserInformation.USER_NAME);

                JSONObject resultJson = new JSONObject();
                resultJson.put("objid", -1);
                resultJson.put("fixcolumn", fixColumn);
                resultJson.put("isWMSCheck", "N");
                resultJson.put("table", "DL_B_INV_ADJ");
                accesLogger.info("WmsTranUpdateSaveCmdImpl--resultJson_save-->{}",resultJson);
//                log.info("SaveJson==>" + resultJson.toString());
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlOrderIn", new HashMap(16));
                event.put("param", resultJson);
                querySession.setEvent(event);
                //1.保存服务
                if (0 == state) {
                    int count = wmsdlUpdateMapper.selectWmsCount(wms_bill_no);
                    if(count<=0){
                        JSONObject retJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
                        accesLogger.info("WmsTranUpdateSaveCmdImpl--retJo-->{}",retJo);
//                        log.debug("调整单保存返回参数" + retJo.toJSONString());

                        if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                            throw new NDSException("保存失败:" + retJo.get("message") + retJo.get("error") + retJo.get("data"));
                        }
                        objid = retJo.getLong("objid");
                        if (objid == null) {
                            JSONObject retData = retJo.getJSONObject("data");
                            objid = retData.getLong("objid");
                        }
                        state = 1;
                        stateObj.put("objid", objid);
                        stateObj.put("state", state);
                    }
                }
                queryDataArray.add(resultJson);
                //2.提交服务
                if (1 == state) {
                    int status = wmsdlUpdateMapper.selectWmsStatus(wms_bill_no);
                    if(status!=2) {
                        resultJson.put("objid", objid);
                        resultJson.put("USER", fixColumn.getJSONObject("USER"));
                        event.put("param", resultJson);
                        accesLogger.info("WmsTranUpdateSaveCmdImpl--resultJson_submit-->{}",resultJson);

                        querySession.setEvent(event);
                        JSONObject subJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "submit");
                        accesLogger.info("WmsTranUpdateSaveCmdImpl--subJo-->{}",subJo);

                        if (subJo.get("code") != null && (int) subJo.get("code") < 0) {
                            throw new NDSException("提交失败:" + subJo.get("message") + subJo.get("error") + subJo.get("data"));
                        }
                        state = 2;
                        stateObj.put("state", state);
                        stateObj.put("objid", objid);
                    }
                }
                //3.验收服务
                int accepte_status = wmsdlUpdateMapper.selectWmsAccepteSta(wms_bill_no);
                if(accepte_status!=2) {
                    resultJson.put("objid", objid);
                    resultJson.put("USER", fixColumn.getJSONObject("USER"));
                    event.put("param", resultJson);
                    accesLogger.info("WmsTranUpdateSaveCmdImpl--resultJson_accept-->{}",resultJson);

                    event.setParameter("command", "com.jackrain.nea.dl.inv.api.BinvAdjPandAcceptCmd:1.0:dl");
                    event.setParameter("table", "DL_B_INV_ADJ");
                    event.setParameter("webaction", "PAND_ADJ_OBJ_CHECK");
                    querySession.setEvent(event);

                    JSONObject accJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "webaction");
                    accesLogger.info("WmsTranUpdateSaveCmdImpl--accJo-->{}",accJo);

                    if (accJo.get("code") != null && (int) accJo.get("code") < 0) {
                        throw new NDSException("验收失败:" + accJo.get("message") + accJo.get("error") + accJo.get("data"));
                    }
                    state = 3;
                    stateObj.put("state", state);
                    stateObj.put("id", billnoid);
                    stateObj.put("objid", objid);
                    succesIdArray.add(stateObj);
                }
            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("id", billnoid);
                errrobj.put("state", state);
                errrobj.put("objid", objid);
                errArray.add(errrobj);
            }
        }

        if (errArray.size() > 0) {
            vh.put("error", errArray);
            vh.put("success", succesIdArray);
            vh.put("code", -1);
        } else {

            vh.put("success", succesIdArray);
            vh.put("code", 0);
        }
        vh.put("queryDataArray",queryDataArray);
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
//        log.debug("---------库存调整单库执行时间--------->>" + spendTime);
        return vh;
    }

    /**
     * 数据整合
     *
     * @param oldJo          主表数据
     * @param purInItemArray 子表数据
     * @return JSONObject
     */
    public JSONObject dataConversion(JSONObject oldJo, JSONArray purInItemArray, WmsOrderInMapper wmsOrderInMapper) {

        //翻译主表
        JSONObject newJo = new JSONObject();
        newJo.put("WMS_BILL_NO", oldJo.getString("WMS_BILL_NO"));
        String adjType = oldJo.getString("ADJ_REASON");
        String typeEcode = null;
        if ("库存盘点".equals(adjType)) {
            typeEcode = "001";
        } else if ("二次售卖".equals(adjType)) {
            typeEcode = "013";
        } else if ("报废专用".equals(adjType)) {
            typeEcode = "014";
        } else {
            typeEcode = "000";
        }
//        else if ("串色串码".equals(adjType)) {
//            typeEcode = "003";
//        }
        Long adiTypeid = wmsOrderInMapper.selectAdiTypeId(typeEcode);
        if (adiTypeid == null) {
            throw new NDSException("查询不到对应的调整原因ID！");
        }
        newJo.put("ADJ_TYPE", adiTypeid);
        if ("001".equals(adjType)) {
            newJo.put("INV_ADJ_TYPE", "PAND");
        } else {
            newJo.put("INV_ADJ_TYPE", "INV_ADJ");
        }
        newJo.put("IS_WMS", "Y");
        String storeDestStr = oldJo.getString("STORE_ECODE");
        if (null != storeDestStr) {

            JSONObject whereJo2 = new JSONObject();
            whereJo2.put("ECODE", storeDestStr);
            JSONObject cpmap2 = postQueryEvemt.queryCP("CP_C_STORE", "ID", whereJo2);
            if (cpmap2 == null) {
                throw new NDSException(storeDestStr + "店仓编码查不到对应的店仓ID！");
            }
            Long cpstoreid = TypeUtils.castToLong(cpmap2.getLong("ID"));
            newJo.put("CP_C_STORE_ID", cpstoreid);

        }

        newJo.put("REMARK", oldJo.getString("REMARK"));
        JSONObject userJo = new JSONObject();
        userJo.put("NAME", oldJo.getString("MODIFIER_ENAME"));
        userJo.put("ENAME", oldJo.getString("MODIFIER_NAME"));

        String ownername = UserInformation.USER_NAME;
        JSONObject whereJo3 = new JSONObject();
        whereJo3.put("NAME", ownername);
        JSONObject cpmap3 = postQueryEvemt.queryCP("USERS", "ID", whereJo3);
        Long ownerid = TypeUtils.castToLong(cpmap3.getLong("ID"));
        userJo.put("ID", ownerid);

        JSONArray itemArray = new JSONArray();
        for (int a = 0; a < purInItemArray.size(); a++) {

            JSONObject oldItemJo = purInItemArray.getJSONObject(a);
            JSONObject newItemJo = new JSONObject();
            newItemJo.put("ID", -1);
            newItemJo.put("QTY_BILL", oldItemJo.getString("QTY_BILL"));
            newItemJo.put("PS_C_SKU_ECODE", oldItemJo.getString("SKU"));
            itemArray.add(newItemJo);
        }

        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_INV_ADJ", newJo);
        fixColumn.put("DL_B_INV_ADJ_ITEM", itemArray);
        fixColumn.put("USER", userJo);

        return fixColumn;

    }


    /**
     * ES查询
     *
     * @param billNo 单据编号
     * @return id
     */
    public JSONObject es(String billNo) {
        JSONObject bill_no = esUtil.generateMatch("BILL_NO", billNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(btranEsName.getIndex(),
                    btranEsName.getIntype(), "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    private JSONObject billdata(JSONObject esData) {
        JSONObject hits = esData.getJSONObject("hits");
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject sourceJson = hitsArray.getJSONObject(0);

        JSONObject source = sourceJson.getJSONObject("_source");

        return source;
    }


    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }


}
